<template>
  <v-card
    class="mx-auto"
    max-width="600"
  >
    <v-toolbar density="compact"
               variant="solo"
    >
      <v-text-field
        v-model="tempTag"
        density="compact"
        variant="solo"
        clearable
        hide-details="auto"
        label="Custom Tags"

        @click:clear="searchTags()"

      >
        <template v-slot:append-inner>
          <v-btn density="compact"
                 icon="mdi-file-plus" @click="addTag"></v-btn>
        </template>
      </v-text-field>

    </v-toolbar>

    <div class="tagsList">
      <v-list density="compact">
        <v-list-item v-for="(item, index) in tags" :key="item"
                     active-color="primary"
                     variant="tonal"
                     style="margin: 5px"
        >
          <v-list-item-title>
            <v-text-field
              v-model="item.en"
              density="compact"
              variant="solo"
              hide-details="auto"
              readonly
              label="Tag">
            </v-text-field>
          </v-list-item-title>
          <v-list-item-subtitle>
            <v-text-field
              v-model="item.cn"
              density="compact"
              variant="solo"
              hide-details="auto"
              label="Translation" @change="updateTag(item)">
            </v-text-field>
            <v-text-field
              v-model="item.type"
              density="compact"
              variant="solo"
              hide-details="auto"
              label="Type" @change="updateTag(item)">
            </v-text-field>
          </v-list-item-subtitle>


          <v-list-item-action>

            <v-switch
              color="primary"
              label="on"
              true-value="Enable"
              false-value="Disable"
              v-model="item.state"
              density="compact" @change="updateTag(item)"

            >
              <template v-slot:label>
                {{ item.state }}
              </template>
              <template v-slot:append>

                <v-spacer/>
                <v-icon density="compact" @click="deleteTag(item)">mdi-delete</v-icon>
              </template>
            </v-switch>

          </v-list-item-action>
        </v-list-item>
      </v-list>
    </div>


  </v-card>
</template>
<script setup>
import {inject, ref, watch} from 'vue';
import {openDB} from 'idb';

const DB_NAME = 'custom-tag-db';
const STORE_NAME = 'custom-tag-store';

const dbPromise = openDB(DB_NAME, 1, {
  upgrade(db) {
    const objectStore = db.createObjectStore(STORE_NAME, {keyPath: 'en'});
    objectStore.createIndex('en', 'en');
  },
});

const IndexedDB = {

  async getAllTags() {
    const db = await dbPromise;
    const tx = db.transaction(STORE_NAME, 'readonly');
    const store = tx.objectStore(STORE_NAME);
    return store.getAll();
  },
  async addTag(tag) {
    const db = await dbPromise;
    const tx = db.transaction(STORE_NAME, 'readwrite');
    const store = tx.objectStore(STORE_NAME);
    const id = uuidv4();
    await store.add({...tag});
    return tx.complete;
  }
  ,

  async updateTag(tag) {
    const db = await dbPromise;
    const tx = db.transaction(STORE_NAME, 'readwrite');
    const store = tx.objectStore(STORE_NAME);
    const updateTag = {...tag, updated: new Date()};
    await store.put(updateTag);
    return tx.complete;
  }
  ,

  async deleteTag(en) {
    const db = await dbPromise;
    const tx = db.transaction(STORE_NAME, 'readwrite');
    const store = tx.objectStore(STORE_NAME);
    await store.delete(en);
    return tx.complete;
  }
  ,

  async searchTags(query) {
    const db = await dbPromise;
    const tx = db.transaction(STORE_NAME, 'readonly');
    const store = tx.objectStore(STORE_NAME);
    const index = store.index('en');
    const results = await index.getAll(IDBKeyRange.bound(query, query + '\uffff'));
    return results;
  }
}

function quickSort(arr) {
  if (arr.length <= 1) {
    return arr;
  }

  const pivotIndex = Math.floor(arr.length / 2);
  const pivot = arr[pivotIndex];
  const less = [];
  const greater = [];

  for (let i = 0; i < arr.length; i++) {
    if (i === pivotIndex) {
      continue;
    }
    // if (arr[i].en > pivot.en) {
    if (arr[i].created > pivot.created) {
      less.push(arr[i]);
    } else {
      greater.push(arr[i]);
    }
  }

  return [...quickSort(less), pivot, ...quickSort(greater)];
}


const customTags = inject('customTags')
const tags = ref([])

const query = ref('');
const editingTag = ref({})

const tempTag = ref('');

watch(tempTag, (tempTag, prevtempTitle) => {
  searchTags(tempTag ? tempTag : '')
  console.log(tempTag + ':' + prevtempTitle)
  editingTag.value = {...emptyTag}
  editingTag.value.en = tempTag ? tempTag : ''

})

watch(tags, (newTags, oldTags) => {
  const tempTag = {}
  for (const tag of newTags) {
    tempTag[tag.en] = tag
  }
  customTags.value = tempTag;


})


const emptyTag = {
  en: '',
  cn: '',
  type: '',
  state: 'Enable'
}


const fetchTags = async () => {


  tags.value = quickSort(await IndexedDB.getAllTags())


};

const searchTags = async () => {

  tags.value = quickSort(await IndexedDB.searchTags(tempTag.value ? tempTag.value : ''));

};

const addTag = () => {
  if (tempTag.value != '') {
    for (const tag of tags.value) {
      if (tag.en == tempTag.value) {
        return
      }
    }
    saveTag();
  }
};

const deleteTag = async (tag) => {
  await IndexedDB.deleteTag(tag.en);
  console.log("delete")
  await searchTags();
};

const saveTag = async () => {

  const newTag = {
    ...editingTag.value,
    created: new Date()
  };

  await IndexedDB.updateTag(newTag);

  await searchTags();

}

const updateTag = async (tag) => {

  editingTag.value = tag

  await saveTag()
}

fetchTags()
</script>


